﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.OleDb;
using System.Collections;
using System.Drawing;
using System.Drawing.Drawing2D;

namespace spbtzb
{
    /// <summary>
    /// Summary description for Common
    /// </summary>
    public class Common
    {
        public static readonly string PARENT_CODE = "NO";
        public Common()
        {
        }
 
        /// <summary>
        /// 拼凑embed的flashvars属性 邵毅
        /// </summary>
        /// <returns></returns>
        public static string GetflashvarsString()
        {
            string flashvars_Pics = "bcastr_file=";
            string flashvars_texts = "bcastr_title=";
            string flashvars_links = "bcastr_link=";

            OleDbDataReader reader;
            OleDbConnection conn = new OleDbConnection(spbtzb.ConString.ConnString);
            reader = AccessHelper.ExecuteReader(conn, CommandType.Text, "SELECT TOP 5 * FROM ImageList WHERE Type='PPT'  AND IsDisplay = true  order by ID desc");

            while (reader.Read())
            {
                flashvars_Pics += "imagesUpload/";
                flashvars_Pics += reader["ImageURL"].ToString();
                flashvars_Pics += "|";
                flashvars_links += reader["LinkURL"].ToString();
                flashvars_links += "|";
                flashvars_texts += reader["Title"].ToString();
                flashvars_texts += "|";
            }

            flashvars_Pics = flashvars_Pics.Substring(0, flashvars_Pics.Length - 1);
            flashvars_links = flashvars_links.Substring(0, flashvars_links.Length - 1);
            flashvars_texts = flashvars_texts.Substring(0, flashvars_texts.Length - 1);
            flashvars_Pics += "&";
            flashvars_links += "&";

            string LastString = "";
            return flashvars_Pics + flashvars_links + flashvars_texts + LastString;
        }

        public static string FormatString(string Str)
        {
            Str = Str.Replace("&", "&amp");
            Str = Str.Replace("'", "''");
            Str = Str.Replace("-", "—");
            Str = Str.Replace("<", "&lt;");
            Str = Str.Replace(">", "&gt;");
            return Str;
        }
        ///   <summary>   
        ///   还原格式化字符串   
        ///   </summary>   
        ///   <param   name="Str"></param>   
        ///   <returns></returns>   
        public static string ToString(string Str)
        {
            Str = Str.Replace("&amp", "&");
            Str = Str.Replace("&sem", ";");
            Str = Str.Replace("''", "'");
            Str = Str.Replace("—", "-");
            Str = Str.Replace("&lt;", "<");
            Str = Str.Replace("&gt;", ">");
            return Str;
        }
        public static string getOneValue(string TempStr)
        {
            if (TempStr.Length > 0)
            {
                TempStr = regularExpressionsOfHTML(TempStr);
                TempStr = TempStr.Substring(0, TempStr.Length - 1);
            }
            return TempStr;
        }
        public static string regularExpressionsOfHTML(string TempContent)
        {
            //TempContent = System.Text.RegularExpressions.Regex.Replace(TempContent,"<[^>]+>",""); //任意多个

            TempContent = ToString(TempContent);
            TempContent = System.Text.RegularExpressions.Regex.Replace(TempContent, "<[^>]*>", ""); //匹配一个
            TempContent = TempContent.Replace("&nbsp;"," ");
            return TempContent;
        } 


        public static string CutString(string title)
        {
            return CutString(title,14);
        }
        public static string CutString(string str, int length)
        {
            if (str.Length > length)
            {
                str = str.Substring(0, length - 3) + "...";
            }
            return str;
        }
        public static Hashtable GetContentTypeTable()
        {
            if (HttpContext.Current.Cache.Get("ParentType") != null)
            {
                return (Hashtable)HttpContext.Current.Cache.Get("ParentType");
            }
            else
            {
                //string strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='E://spbtzb.mdb';";
                string strConnection = spbtzb.ConString.ConnString;
                DataTable dt = spbtzb.AccessHelper.ExecuteDataTable(strConnection, CommandType.Text,
                                       "SELECT TypeCode, TypeName FROM ContentType");
                Hashtable hash = new Hashtable();
                foreach (DataRow dr in dt.Rows)
                {
                    hash.Add(dr[0].ToString(), dr[1].ToString());
                }
                HttpContext.Current.Cache["ParentType"] = hash;
                return hash;
            }
        }

        public static Hashtable GetParentTypeTable()
        {
            if (HttpContext.Current.Cache.Get("ContentType") != null)
            {
                return (Hashtable)HttpContext.Current.Cache.Get("ContentType");
            }
            else
            {
                string strConnection = ConString.ConnString;
                DataTable dt = spbtzb.AccessHelper.ExecuteDataTable(strConnection, CommandType.Text,
                                       "SELECT TypeCode, ParentType FROM ContentType WHERE ParentType <> '" + PARENT_CODE + "'");
                Hashtable hash = new Hashtable();
                foreach (DataRow dr in dt.Rows)
                {
                    hash.Add(dr[0].ToString(), dr[1].ToString());
                }
                HttpContext.Current.Cache["ContentType"] = hash;
                return hash;
            }
        }
        public static void UpdateCacheFromDB()
        {
            string strConnection = ConString.ConnString;
            DataTable dt = spbtzb.AccessHelper.ExecuteDataTable(strConnection, CommandType.Text,
                                   "SELECT TypeCode, ParentType FROM ContentType WHERE ParentType <> '" + PARENT_CODE + "'");
            Hashtable hash = new Hashtable();
            foreach (DataRow dr in dt.Rows)
            {
                hash.Add(dr[0].ToString(), dr[1].ToString());
            }
            HttpContext.Current.Cache["ContentType"] = hash;

            DataTable dt1 = spbtzb.AccessHelper.ExecuteDataTable(strConnection, CommandType.Text,
                                   "SELECT TypeCode, TypeName FROM ContentType");
            Hashtable hash1 = new Hashtable();
            foreach (DataRow dr in dt1.Rows)
            {
                hash1.Add(dr[0].ToString(), dr[1].ToString());
            }
            HttpContext.Current.Cache["ParentType"] = hash1;
        }


        public static string GetTypeNameByCode(string typeCode)
        {
            Hashtable hash = GetContentTypeTable();
            if (hash[typeCode] == null)
            {
                return null;
            }
            return hash[typeCode].ToString();
        }
        public static string GetParentTypeCode(string typeCode)
        {
            Hashtable hash = GetParentTypeTable();
            if (hash[typeCode] == null)
            {
                return null;
            }
            return hash[typeCode].ToString();
        }
        public static string GetParentNameByCode(string typeCode)
        {
            return GetTypeNameByCode(GetParentTypeCode(typeCode));
        }

        /// <summary> 
        /// 按比例缩小图片，自动计算宽度 
        /// </summary> 
        /// <param name="stroldpic">源图文件名(包括路径)</param> 
        /// <param name="strnewpic">缩小后保存为文件名(包括路径)</param> 
        /// <param name="intheight">缩小至高度</param> 
        public static void SmallPic(string stroldpic, string strnewpic, int intheight,int intwidth)
        {
            System.Drawing.Bitmap objpic, objnewpic;
            try
            {
                objpic = new System.Drawing.Bitmap(stroldpic);
                
                //float fWidth = ((float)intheight / (float)objpic.Height) * (float)objpic.Width;
                //int intwidth = Convert.ToInt32(fWidth);
                objnewpic = new System.Drawing.Bitmap(objpic, intwidth, intheight);
                objnewpic.Save(strnewpic);
               

            }
            catch (Exception exp) { throw exp; }
            finally
            {
                objpic = null;
                objnewpic = null;
            }
        }

        /// <summary>
        /// 生成缩略图（低质量)  
        /// </summary>
        /// <param name="ImgStream"></param>
        /// <param name="Path"></param>
        public static void SaveLowQualityThumbNail(System.IO.Stream ImgStream, string Path)
        {
            int width = 229;
            int height = 189;

            System.Drawing.Image oImg= System.Drawing.Image.FromStream(ImgStream);

            int widthScale = oImg.Width / width;
            int heightScale = oImg.Height / height;
            int Scale;
            if (widthScale > heightScale)
                Scale = widthScale;
            else
                Scale = heightScale;

            oImg = oImg.GetThumbnailImage(oImg.Width / Scale, oImg.Height/Scale, null, IntPtr.Zero);
            //string strGuid = System.Guid.NewGuid().ToString().ToLower();
            //string strFileExt = //strFileName.Substring(strFileName.LastIndexOf("."));
            //Response.ContentType = strContentType;
            //MemoryStream MemStream = new MemoryStream();
            oImg.Save(Path);
        }

        /// <summary> 
        /// 生成缩略图
        /// 长宽比例不变
        /// 可通过宽度和高度改变质量
        /// </summary>   
        /// <param name="SourceFile">文件在服务器上的物理地址</param>   
        /// <param name="strSavePathFile">保存在服务器上的路径</param>   
        /// <param name="ThumbWidth">宽度</param>   
        /// <param name="ThumbHeight">高度</param>   
        /// <param name="BgColor">背景</param>   
        public static void SaveHightQualityThumbnail(System.IO.Stream ImgStream, string strSavePathFile, float ThumbWidth, float ThumbHeight, string BgColor)
        {
            System.Drawing.Image oImg = System.Drawing.Image.FromStream(ImgStream);
            //小图   
            int intWidth, intHeight;
            float QriginalWidth = (float)oImg.Width;
            float QriginalHight = (float)oImg.Height;
            float widthScale = QriginalWidth / ThumbWidth;
            float heightScale = QriginalHight / ThumbHeight;
            float Scale;
            if (widthScale > heightScale)
            {
                //Scale = widthScale;
                intWidth = (int)(QriginalWidth / widthScale);
                intHeight = (int)(QriginalHight / widthScale);
            }
            else
            {
                intWidth = (int)(QriginalWidth / heightScale);
                intHeight = (int)(QriginalHight / heightScale);
            }

            //if (oImg.Width > oImg.Height)
            //{
            //    if (oImg.Width > ThumbWidth)
            //    {
            //        intwidth = ThumbWidth;
            //        intheight = (oImg.Height * ThumbWidth) / oImg.Width;
            //    }
            //    else
            //    {
            //        intwidth = oImg.Width;
            //        intheight = oImg.Height;
            //    }
            //}
            //else
            //{
            //    if (oImg.Height > ThumbHeight)
            //    {
            //        intwidth = (oImg.Width * ThumbHeight) / oImg.Height; intheight = ThumbHeight;
            //    }
            //    else
            //    {
            //        intwidth = oImg.Width; intheight = oImg.Height;
            //    }
            //}
            //构造一个指定宽高的Bitmap   
            Bitmap bitmay = new Bitmap(intWidth, intHeight);
            Graphics g = Graphics.FromImage(bitmay);
            Color myColor;
            if (BgColor == null) myColor = Color.FromName("white");
            else
                myColor = Color.FromName(BgColor);
            //用指定的颜色填充Bitmap   
            g.Clear(myColor);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            //开始画图   
            g.DrawImage(oImg, new Rectangle(0, 0, intWidth, intHeight), new Rectangle(0, 0, oImg.Width, oImg.Height), GraphicsUnit.Pixel);
            bitmay.Save(strSavePathFile);
            g.Dispose();
            bitmay.Dispose();
            oImg.Dispose();
        }  
    }
}
